/**
 * 
 */
package com.yangtao.prototype.system.role.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.yangtao.framework.service.BaseService;
import com.yangtao.framework.util.StringHelper;
import com.yangtao.prototype.system.dao.MenuTreeDAO;
import com.yangtao.prototype.system.dao.RoleDAO;
import com.yangtao.prototype.system.entity.MenuTree;
import com.yangtao.prototype.system.role.service.RoleModel;
import com.yangtao.prototype.system.role.service.RoleService;
import com.yangtao.prototype.util.CheckBoxTree;

/**
 * 角色管理类
 * 
 * @author 杨涛
 * 
 */
@Service
public class RoleServiceImpl extends BaseService implements RoleService {
	@Autowired
	private MenuTreeDAO mtd;
	@Autowired
	private RoleDAO rd;

	/**
	 * 加载所有菜单
	 */
	@Override
	public RoleModel loadMenus(RoleModel model) {
		List<CheckBoxTree> trees = new ArrayList<CheckBoxTree>();
		String roleId = model.getDomain().getId();
		List<MenuTree> menus = mtd.findAllMenus();
		Set<String> set = rd.loadAuthorizedMenu(roleId);
		for (MenuTree mt : menus) {
			trees.add(CheckBoxTree.loadFromMenu(mt, set));
		}
		model.setMenu(trees);
		return model;
	}

	/**
	 * 保存角色权限
	 */
	@Override
	public RoleModel saveRoleAuth(RoleModel model) {
		Assert.notNull(model.getRoleAuth(), "菜单权限不能为空");
		String[] auths = model.getRoleAuth().split(",");
		rd.addRoleAuth(model.getDomain(), auths);
		model.addInfo("save.success");
		return model;
	}

	@Override
	public RoleModel list(RoleModel model) {
		rd.findPageByExample(model.getPage(), model.getDomain());
		return model;
	}

	@Override
	public RoleModel load(RoleModel model) {
		if (StringHelper.isNotEmpty(model.getDomain().getId())) {
			model.setDomain(rd.load(model.getDomain().getId()));
		}
		return model;
	}

	@Override
	public RoleModel delete(RoleModel model) {
		if (model.getDomain().getUsers() != null
				&& model.getDomain().getUsers().size() > 0) {
			model.addError("不能删除");
			return model;
		}
		rd.delete(model.getDomain());
		model.addInfo("delete.success");
		return model;
	}

}
